/**
 * Created by Nico on 2015/12/25.
 */
var async = require('async');
var AV = require('leanengine');
var Q = require('q') ;
var ActivityResult = AV.Object.extend('ActivityResult');
var ActivityInfo = AV.Object.extend('Config');
var UserCoupon = AV.Object.extend('UserCoupon');
var Coupons = AV.Object.extend('Coupons');
var User = AV.Object.extend('_User');
var PointFlow = AV.Object.extend('PointFlow');
var AmountFlow = AV.Object.extend('AmountFlow');
var GoodsFlow = AV.Object.extend('GoodsFlow');

var ActivityShare = AV.Object.extend('ActivityShare');
var ActivityShareList = AV.Object.extend('ActivityShareList');
var GCoinFlow = AV.Object.extend('GCoinFlow')

var cartCtrl =require('./cart.js');
module.exports = {
    //获取activity表turntable数据
    getTurntableInfo:function(){
        var query = new AV.Query(ActivityInfo);
        query.equalTo("key","turntable");
        return query.first();
    },
    //获取当天累计抽奖次数
    getAllTimesByDay:function(uid){
        var promise = new AV.Promise();
        async.waterfall([
            //查找最新的updateAt，判断是否为当天
            function(callback){
                var query = new AV.Query(ActivityResult);
                query.equalTo("uid",uid+"");
                query.descending("updatedAt");
                query.first().then(function(data){
                    callback(null, data);
                });
            },
            function(data,callback){
                if(data){
                    var updatedAt = data.updatedAt ;
                    if(new Date().toDateString() === new Date(updatedAt).toDateString()){
                        //true：同一天
                        callback(null, {oneDay:data.get('time'),time:data.get('time'),restTime:data.get('restTime')})
                    }else{
                        //非同一天，返回count为0
                        callback(null, {oneDay:0,time:data.get('time'),restTime:data.get('restTime')});
                    }
                }else{
                    callback(null, {oneDay:0,time:0,restTime:0});
                }
            }
        ],function(err,result){
            if(err){
                promise.reject(err);
            }else{
                promise.resolve(result);
            }
        });
        return promise;
    },
    //向ActivityResults表中插入/更新数据
    insertTimeToResult:function(uid,rewardLevel,activityName,time){
        var promise = new AV.Promise();
        async.waterfall([
            //查找最新的updateAt，判断是否为当天
            function(callback){
                var query = new AV.Query(ActivityResult);
                query.equalTo("uid",uid+"");
                query.descending("updatedAt");
                if(time === -2 ){
                    query.notEqualTo('restTime',0);
                }else{
                    query.equalTo('restTime',0);
                }
                query.first().then(function(data){
                    callback(null, data);
                });
            },
            function(data,callback){
                var updateData = {insert:-1,update:-1} ;
                //console.log(data);
                if(data){
                    var updatedAt = data.updatedAt ;
                    if(time === -2){
                        //直接插入或者更新数据
                        updateData['update'] = 0;
                    }else{
                        if(new Date().toDateString() === new Date(updatedAt).toDateString()){
                            //true：同一天，计算createdAt和updatedAt之间的count
                            if(time != -1){
                                if(data.get('time') < time){
                                    //可以更新
                                    updateData['update'] = 0;
                                }
                            }else{
                                //可以更新
                                updateData['update'] = 0;
                            }
                        }else{
                            //非同一天,创建一条新记录
                            updateData['insert'] = 0;
                        }
                    }
                }else{
                    updateData['insert'] = 0;
                }
                callback(null, updateData,data);
            },
            //插入或者更新数据
            function(updateData,data,callback){
                //console.log(updateData);
                if(updateData.insert===0){
                    var act = new ActivityResult();
                    act.set('uid',uid+"");
                    act.add('rewardLevel',rewardLevel);
                    act.increment('time');
                    if(time === -2){
                        act.increment('restTime');
                    }else{
                        act.set('restTime',0);
                    }
                    act.set('activityName',activityName+"");
                    act.save().then(function(){
                        callback(null, {code:1,msg:'插入成功'})
                    });
                }else if(updateData.update===0){
                    data.increment('time');
                    data.add('rewardLevel',rewardLevel);
                    data.save().then(function(){
                        callback(null, {code:2,msg:'更新成功'})
                    });
                }else{
                    callback(null, {code:3,msg:'您已达上限，明天再来吧'})
                }
            }
        ],function(err,result){
            if(err){
                promise.reject(err);
            }else{
                promise.resolve(result);
            }
        });
        return promise;
    },
    //发放优惠券
    giveCoupons:function(uid,couponsId){
        var timestamp = Date.parse(new Date(new Date().setHours(23,59,59)));
        var startTime = Date.parse(new Date());

        var promise = new AV.Promise();
        async.waterfall([
            //判断优惠券是否存在
            function(callback){
                var query = new AV.Query(Coupons);
                query.get(couponsId+"").then(function(res){
                    if(res){
                        callback(null,res);
                    }else{
                        callback({code:1047,msg:"优惠券未设置"});
                    }
                }).catch(function(err){
                    callback({code:1047,msg:"优惠券未设置"});
                });
            },
            //发放优惠券
            function(res,callback){
                var takeCoupon = new UserCoupon();
                //var endVaildTime=String(timestamp+3*3600*24*1000);
                var endVaildTime=String(timestamp);    //当天24点前有效
                var newCoupon={'uid':uid,'cid':res.get("batchNo"),GiveTime:new Date(),'validityEndPeriod':endVaildTime,'used':0,'status':1,coupon:res.attributes,validityStartPeriod:String(startTime)};
                takeCoupon.save(newCoupon).then(function(res){
                    callback(null,{code:0,msg:"发放成功",res:res});
                });
            }
        ],function(err,result){
            if(err){
                promise.reject(err);
            }else{
                promise.resolve(result);
            }
        });
        return promise;
    },
    //发放现金
    giveCash:function(uid,cash){
        var timestamp = Date.parse(new Date());
        var promise = new AV.Promise();
        async.waterfall([
            function(callback){
                var query = new AV.Query(User);
                var newAmount = 0 ;
                var oldAmount = 0 ;
                query.get(uid).then(function(res){
                    if(res){
                        oldAmount = parseFloat(res.get('gCoin')) ;
                        newAmount = oldAmount+parseFloat(cash) ;
                        res.save({gCoin:newAmount}).then(function(){
                            callback(null,{user:res,newAmount:newAmount,oldAmount:oldAmount});
                        }).catch(function(err){
                            callback({code:-1,msg:'保存失败'});
                        });

                    }else{
                        callback({code:-1,msg:'用户不存在'});
                    }
                });
            },
            //发放现金
            function(res,callback){
                var amountFlow = new GCoinFlow();
                amountFlow.save({
                    content: "抽奖奖励现金充值+"+cash+"元",
                    userid:uid,
                    newamount: parseFloat(cash),
                    beforeamount: res.oldAmount,
                    afteramount:res.newAmount
                }, {
                    success: function(post) {
                        callback(null,{code:0,msg:"发放成功",res:res});
                    },
                    error: function(post, error) {
                        callback(null,{code:0,msg:"发放失败",res:res});
                    }
                });
            }
        ],function(err,result){
            if(err){
                promise.reject(err);
            }else{
                promise.resolve(result);
            }
        });
        return promise;
    },
    //发放积分
    givePoint:function (uid,point) {
        var promise = new AV.Promise();
        async.waterfall([
            //获取用户信息
            function(callback){
                var query = new AV.Query(User);
                query.get(uid+"").then(function(res){
                    var beforepoint = res.get('point');
                    res.set('point',beforepoint+parseInt(point));
                    res.save();
                    callback(null,parseInt(point),beforepoint);
                }).catch(function(err){
                    //console.log(err);
                    callback({code:1050,msg:"uid用户不存在",err:err});
                });
            },
            //记录积分流水
            function(point,beforepoint,callback){
                var pointFlow = new PointFlow();
                pointFlow.save({
                    content: "抽奖奖励积分+"+parseInt(point),
                    userid: uid,
                    newpoint: parseInt(point),
                    beforepoint: beforepoint,
                    afterpoint: beforepoint + parseInt(point)
                }, {
                    success: function(pointflow) {
                        callback(null,{code:0,msg:"领取积分奖励成功"});
                    },
                    error: function(pointflow, error) {
                        callback(null,{code:0,msg:"领取积分奖励成功,流水记录失败！"});
                    }
                });
            },
        ],function(err,result){
            if(err){
                promise.reject(err);
            }else{
                promise.resolve(result);
            }
        });
        return promise;
    },
    //发放礼品券
    giveGiftToCart:function(uid,pid,psid){
        var promise = new AV.Promise();
        if(uid && pid && psid){
            async.waterfall([
                function(callback){
                    cartCtrl.insertProToCart(pid,psid,1,uid,'3').then(function(resCart){
                        callback(null,resCart);
                    }).catch(function(err){
                        callback({code:-3,msg:'抽奖礼品加入购物车失败'});
                    })
                },
                function(data,callback){
                    if(data.code === 0){
                        //插入流水
                        var goodsFlow = new GoodsFlow();
                        goodsFlow.set('uid',uid+"");
                        goodsFlow.set('pid',pid+"");
                        goodsFlow.set('psid',psid+"");
                        goodsFlow.set('remark','');
                        goodsFlow.save().then(function(){
                            callback(null, {code:0});
                        }).catch(function(err){
                            callback({code:-1});
                        });
                    }else{
                        callback({code:-1});
                    }
                }
            ],function(err,result){
                if(err){
                    promise.reject(err);
                }else{
                    promise.resolve({code:0,msg:"已成功领取抽奖礼物"});
                }
            });
            return promise;
        }else{
            return new AV.Promise.error('userid or GiftGiveID should not be empty');
        }
    },

    cutPoint:function(uid,point){
        var promise = new AV.Promise();
        async.waterfall([
            function(callback){
                var query = new AV.Query(User);
                query.get(uid).then(function(res){
                    var newPoint = parseInt(res.get('point'))-parseInt(point);
                    if(newPoint<0){
                        //积分不足，退出程序
                        return callback({code:-1,msg:'积分不足'})
                    }
                    var oldPoint = parseInt(res.get('point'));
                    res.save({point:newPoint}).then(function(){
                        callback(null, {code:0,userInfo:res,point:point,newPoint:newPoint,oldPoint:oldPoint});
                    }).catch(function(){
                        callback(null,{code:1})
                    });
                }).catch(function(){
                    callback(null,{code:1})
                });
            },
            //记录积分流水
            function(user,callback){
                if(user.code === 0){
                    var pointFlow = new PointFlow();
                    pointFlow.save({
                        content: new Date().toFormat("YYYY/MM/DD")+"抽奖扣除积分-"+parseInt(user.point),
                        userid: uid,
                        newpoint: parseInt(-user.point),
                        beforepoint: user.oldPoint,
                        afterpoint: parseInt(user.newPoint)
                    }, {
                        success: function(pointflow) {
                            callback(null,{code:0,msg:"扣减成功"});
                        },
                        error: function(pointflow, error) {
                            callback(null,{code:0,msg:"扣减成功,流水记录失败！"});
                        }
                    });
                }else{
                    callback(null,{code:1});
                }

            },
        ],function(err,result){
            if(err){
                promise.reject(err)
            }else{
                promise.resolve(result);
            }
        });
        return promise;
    },
    /**
     * 根据shareid获取记录
     * @param shareid
     * @returns {*|promise}
     */
    queryActivityShare:function(shareid){
        var promise = new AV.Promise();
        var query = new AV.Query(ActivityShare);
        query.get(shareid+'').then(function(data){
            if(data){
                promise.resolve({code:0,data:data});
            }else{
                promise.resolve({code:1});
            }

        }).catch(function(err){
            promise.reject({code:-1,msg:err});
        });
        return promise;
    },
    /**
     * 根据openid获取数量
     * @param shareid
     * @returns {Query}
     */
    countActivityShareByOpenid:function(openid){
        var query = new AV.Query(ActivityShare);
        query.equalTo('openid',openid+'');
        query.greaterThan('createdAt',new Date(new Date().toDateString()));
        //console.log(new Date(new Date().toDateString()));
        return query.count();
    },
    createShare:function(openid,nickname,image){
        var share = new ActivityShare();
        share.set('openid',openid);
        share.set('nickname',nickname);
        share.set('image',image);
        return share.save();
    },
    isTurntabledInShare:function(openid,shareid){
        var query = new AV.Query(ActivityShareList);
        query.equalTo('shareid',shareid);
        query.equalTo('openid',openid);
        return query.first();
    },
    createShareList:function(openid,nickname,image,shareid,remark){
        var shareList = new ActivityShareList();
        shareList.set('openid',openid);
        shareList.set('nickname',nickname);
        shareList.set('image',image);
        shareList.set('shareid',shareid);
        shareList.set('remark',remark || "谢谢参与");
        return shareList.save();
    },
    queryShareList:function(){ //shareid
        //根据shareid获取全部中奖信息
        var query = new AV.Query(ActivityShareList);
        //query.equalTo('shareid',shareid);
        query.notEqualTo('remark','新年快乐！');
        query.addDescending('createdAt');
        query.limit(10);
        return query.find();
    },
    countShareListByShareid:function(shareid){
        var query = new AV.Query(ActivityShareList);
        query.equalTo('shareid',shareid);
        return query.count();
    },
    queryShareFirst:function(openid){
        var promise = new AV.Promise();
        async.waterfall([
            function(callback){
                var query = new AV.Query(ActivityShare);
                query.equalTo('openid',openid);
                query.first().then(function(data){
                    if(data){
                        callback(null, data);
                    }else{
                        callback({code:-1});
                    }
                });
            },
            function(data,callback){
                var query = new AV.Query(ActivityShareList);
                query.equalTo('shareid',data.id);
                query.find().then(function(list){
                    callback(null, {share:data,shareList:list});
                });
            }
        ],function(err,result){
            if(err){
                promise.reject(err);
            }else{
                promise.resolve(result);
            }
        });
        return promise;
    },
    countReward:function(remark){
        var query = new AV.Query(ActivityShareList);
        query.equalTo('remark',remark);
        return query.count() ;
    },
    saveReward:function(rewards){
        var promise = new AV.Promise();
        var ActivityRewards = AV.Object.extend('ActivityRewards');
        var re = new AV.Query(ActivityRewards);
        re.first().then(function(data){
            if(data){
                data.save(rewards).then(function(){
                    promise.resolve({code:0});
                });
            }else{
                var res = new ActivityRewards();
                res.save(rewards).then(function(){
                    promise.resolve({code:0});
                });
            }
        });
        return promise ;
    },
    queryReward:function(){
        var ActivityRewards = AV.Object.extend('ActivityRewards');
        var query = new AV.Query(ActivityRewards);
        return query.first();
    },


};